package com.wayne.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wayne.blog.common.Ret;
import com.wayne.blog.entity.Article;
import com.wayne.blog.service.ArticleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Lang
 * @since 2025/06/06
 *
 * 文章
 */
@RestController
@RequestMapping("/api/articles")
public class ArticleController {

    private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);

    @Autowired
    private ArticleService articleService;

    @GetMapping("/list")
    public Ret<Page<Article>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) String keyword) {
        Page<Article> page = articleService.getArticlePage(new Page<>(current, size), categoryId, keyword);
        return Ret.success(page);
    }

    @GetMapping("/{id}")
    public Ret<Article> getById(@PathVariable Long id) {
        Article article = articleService.getArticleDetail(id);
        return Ret.success(article);
    }

    @GetMapping("/related/{id}")
    public Ret<List<Article>> getRelatedArticles(@PathVariable Long id) {
        List<Article> articles = articleService.getRelatedArticles(id);
        return Ret.success(articles);
    }

    @PostMapping
    public Ret<?> add(@RequestBody Article article, @RequestParam(value = "tagIds", required = false) List<Long> tagIds) {
        logger.info("添加文章，文章信息：{}，标签ID列表：{}", article, tagIds);
        articleService.saveArticle(article, tagIds);
        return Ret.success();
    }

    @PutMapping("/{id}")
    public Ret<?> update(@PathVariable Long id, @RequestBody Article article, @RequestParam(value = "tagIds", required = false) List<Long> tagIds) {
        logger.info("更新文章，文章ID：{}，文章信息：{}，标签ID列表：{}", id, article, tagIds);
        article.setId(id);
        articleService.updateArticle(article, tagIds);
        return Ret.success();
    }

    @DeleteMapping("/{id}")
    public Ret<?> delete(@PathVariable Long id) {
        articleService.deleteArticle(id);
        return Ret.success();
    }

    @PostMapping("/{id}/like")
    public Ret<?> likeArticle(@PathVariable Long id) {
        logger.info("用户尝试点赞文章，文章ID：{}", id);
        articleService.likeArticle(id);
        return Ret.success("点赞成功");
    }
}